import axios from 'axios'
import { Message, MessageBox } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import Qs from 'qs'
import md5 from 'md5'
// create an axios instance

const getSign = (params, appsecret) => {
  var sorted = Object.keys(params).sort()
  var basestring = appsecret
  for (var i = 0, l = sorted.length; i < l; i++) {
    var k = sorted[i]
    basestring += k + params[k]
  }
  basestring += appsecret
  return md5(basestring).toUpperCase()
}
const service = axios.create({
  baseURL: process.env.API_ROOT, // api 的 base_url
  timeout: 15000,
  paramsSerializer: function(data) {
    let appKey = ''
    let appSecret = ''
    if (typeof (Storage) !== 'undefined') {
      appKey = localStorage.getItem('appkey')
      appSecret = localStorage.getItem('appSecret')
    }
    if (getToken() && !appKey && !appSecret) {
      MessageBox.alert('系统未登录，请重新登录', '错误', {
        confirmButtonText: '确定',
        type: 'error'
      }).then(() => {
        store.dispatch('FedLogOut').then(() => {
          location.reload()
        })
      })
      return Promise.reject('error')
    }
    const timestamp = Date.parse(new Date()) / 1000
    var params = {
      app_key: appKey,
      timestamp: timestamp,
      v: '1.0',
      sign_method: 'md5',
      ...data
    }
    params['sign'] = getSign(params, appSecret)
    return Qs.stringify(params, params) + '&format=json'
  },
  transformRequest: [function(data) {
    var params = {}
    if (data && data.fileType) {
      var formData = data.data
      data = formData
    } else {
      params = {
        ...data
      }
      data = Qs.stringify(params)
    }
    return data
  }]
})
/* 请求前 拦截器 */
service.interceptors.request.use(
  config => {
    // Do something before request is sent
    if (store.getters.token) {
      // 让每个请求携带token-- ['ADMINTOKEN']为自定义key 请根据实际情况自行修改
      config.headers['token'] = getToken()
    }
    return config
  },
  error => {
    // Do something with request error
    Promise.reject(error)
  }
)

/* 响应 拦截器 */
service.interceptors.response.use(
  response => {
    const res = response.data
    if (res.code === 10001) {
      MessageBox.alert('系统未登录，请重新登录', '错误', {
        confirmButtonText: '确定',
        type: 'error'
      }).then(() => {
        store.dispatch('FedLogOut').then(() => {
          location.reload()
        })
      })
      return Promise.reject('error')
    } if (res.code !== 40000 && res.code !== 40003) {
      Message({
        message: res.message,
        type: 'error',
        duration: 5 * 1000
      })
      console.log(Promise.reject(response))
      return Promise.reject(response)
    } else {
      return response
    }
  }, error => {
    Message({
      message: '系统错误，请联系管理员！',
      type: 'error',
      duration: 5 * 1000
    })
    return Promise.reject(error)
  })

export default service
